<?php

namespace common\models\c2\entity;

use Yii;

/**
 * This is the model class for table "{{%card_hold}}".
 *
 * @property string $id
 * @property string $user_id
 * @property string $card_id
 * @property string $buy_at
 * @property integer $usage_time
 * @property string $expired_at
 * @property integer $remain_time
 * @property integer $status
 * @property string $created_at
 * @property string $updated_at
 */
class CardHold extends \kzo\base\models\ActiveRecord
{

    const EVENT_LESSON_CANCEL = "lesson_cancel";

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%card_hold}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'card_id', 'usage_time', 'remain_time'], 'integer'],
            [['buy_at', ], 'required'],
            [['buy_at', 'expired_at', 'created_at', 'updated_at'], 'safe'],
            [['status'], 'integer', 'max' => 4],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'user_id' => Yii::t('app.c2', 'User ID'),
            'card_id' => Yii::t('app.c2', 'Card ID'),
            'buy_at' => Yii::t('app.c2', 'Buy Time'),
            'usage_time' => Yii::t('app.c2', 'Usage Time'),
            'expired_at' => Yii::t('app.c2', 'Expired Time'),
            'remain_time' => Yii::t('app.c2', 'Remain Time'),
            'status' => Yii::t('app.c2', 'Status'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\CardHoldQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\CardHoldQuery(get_called_class());
    }
    
    /**
    * setup default values
    **/
    public function loadDefaultValues($skipIfSet = true) {
        parent::loadDefaultValues($skipIfSet);
    }

    public function getUser()
    {
        return $this->hasOne(FeUser::className(), ['id' => 'user_id']);
    }

    public function getCard()
    {
        return $this->hasOne(Card::className(), ['id' => 'card_id']);
    }

    public function beforeSave($insert)
    {
        if ($insert) {
            /** @var Card $card */
            $card = $this->card;
            $this->usage_time = $card->usage_time;
            $this->remain_time = $card->usage_time;
            $this->expired_at = date("Y-m-d", strtotime("$this->buy_at + $card->expiry_month month"));
        }

        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

}
